﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MirrorFolder
{
    public partial class FormMElementSettings : Form
    {
        bool bOK = false;
        public MElementSettings Sett = null;
        ToolStripButton[] btnDay = new ToolStripButton[7];
        ToolStripButton[] btnHour = new ToolStripButton[24];

        public FormMElementSettings()
        {
            InitializeComponent();
        }

        public bool ShowDialog(MElementSettings sett)
        {
            bOK = false;
            this.Sett = sett;
            BuildHours(new bool[24]);
            BuildDays(new bool[7]);

            txbSourceDir.Text = sett.SourceDir;
            txbDestDir.Text = sett.DestDir;
            rBtnSync.Checked = Sett.Mode == ElementMode.Mirror;
            rBtnArch.Checked = Sett.Mode == ElementMode.Archive;
            chbxDualSync.Checked = Sett.DualSync;
            rBtnArchDiff.Checked = Sett.ArchMode == ArchiveMode.Diff;
            rBtnArchInc.Checked = Sett.ArchMode == ArchiveMode.Inc;
            grArchSettings.Visible = rBtnArch.Checked;
            label9.Text = rBtnArch.Checked ? "Каталог архива" : "Каталог - зеркало";
            numArchLineSize.Value = sett.LineSize;
            numArchLinesCount.Value = sett.LinesCount;

            chbxEnableSchedule.Checked = Sett.Schd.Mode != ScheduleMode.None;
            rBtnDay.Checked = Sett.Schd.Mode == ScheduleMode.EveryDay;
            rBtnHour.Checked = Sett.Schd.Mode == ScheduleMode.EveryHour;
            rBtnPeriod.Checked = Sett.Schd.Mode == ScheduleMode.EveryPeriod;
            pnlEveryDay.Enabled = rBtnDay.Checked;
            pnlEveryHour.Enabled = rBtnHour.Checked;
            pnlEveryPeriod.Enabled = rBtnPeriod.Checked;
            grSchedule.Enabled = chbxEnableSchedule.Checked;

            if (!rBtnDay.Checked)
            {
                for (int i = 0; i < 7; i++) Sett.Schd.DaysOfWeek[i] = true;
                Sett.Schd.TimeOfDay = 0;
            }
            if (!rBtnHour.Checked)
            {
                for (int i = 0; i < 24; i++) Sett.Schd.Hours[i] = true;
                Sett.Schd.Minute = 0;
            }
            if (!rBtnPeriod.Checked)
            {
                Sett.Schd.StartDate = DateTime.Today;
                Sett.Schd.Period = 60;
            }

            for (int i = 0; i < 7; i++) btnDay[i].Checked = Sett.Schd.DaysOfWeek[i];
            for (int i = 0; i < 24; i++) btnHour[i].Checked = Sett.Schd.Hours[i];

            TimeSpan ts = DateTime.MinValue.AddSeconds(Sett.Schd.TimeOfDay) - DateTime.MinValue;
            txbDay_StartTime.Text = string.Format("{0}:{1}", ((int)ts.TotalHours).ToString("00"), ts.Minutes.ToString("00"));
            numHour_Min.Value = Sett.Schd.Minute;
            cldPeriod_StartDate.Value = Sett.Schd.StartDate.Date;
            txbPeriod_StartTime.Text = string.Format("{0}:{1}", Sett.Schd.StartDate.Hour.ToString("00"), Sett.Schd.StartDate.Minute.ToString("00"));
            ts = DateTime.MinValue.AddSeconds(Sett.Schd.Period) - DateTime.MinValue;
            numD.Value = (int)ts.TotalDays;
            numH.Value = ts.Hours;
            numM.Value = ts.Minutes;
            numS.Value = ts.Seconds;

            ShowDialog();
            return bOK;
        }

        void BuildDays(bool[] Days)
        {
            toolDays.Items.Clear();
            for (int i = 0; i < 7; i++)
            {
                string text = i == 0 ? "Пн" : i == 1 ? "Вт" : i == 2 ? "Ср" : i == 3 ? "Чт" : i == 4 ? "Пт" : i == 5 ? "Сб" : "Вс";
                btnDay[i] = CreateButton("btnDay_" + i.ToString(), text, toolDays, btnDay_Click, Days[i]);
            }
        }

        void BuildHours(bool[] Hours)
        {
            toolHour1.Items.Clear();
            toolHour2.Items.Clear();
            toolHour3.Items.Clear();
            toolHour4.Items.Clear();
            for (int i = 0; i < 24; i++)
            {
                ToolStrip tool = i < 6 ? toolHour1 : i < 12 ? toolHour2 : i < 18 ? toolHour3 : toolHour4;
                btnHour[i] = CreateButton("btnHour_" + i.ToString(), i.ToString("00"), tool, btnHour_Click, Hours[i]);
            }
        }

        ToolStripButton CreateButton(string Name, string Text, ToolStrip ParentTool, EventHandler EventClick, bool Checked)
        {
            ToolStripButton btn = new ToolStripButton();
            btn.Name = Name;
            btn.Text = Text;
            btn.CheckOnClick = true;
            btn.Checked = Checked;
            btn.Click += new EventHandler(EventClick);
            ParentTool.Items.Add(btn);
            return btn;
        }

        private void btnDay_Click(object sender, EventArgs e)
        {
            ToolStripButton btn = (ToolStripButton)sender;
            Sett.Schd.DaysOfWeek[Convert.ToInt32(btn.Name.Replace("btnDay_", ""))] = btn.Checked;
        }

        void btnHour_Click(object sender, EventArgs e)
        {
            ToolStripButton btn = (ToolStripButton)sender;
            Sett.Schd.Hours[Convert.ToInt32(btn.Name.Replace("btnHour_", ""))] = btn.Checked;
        }

        private void rBtnDay_CheckedChanged(object sender, EventArgs e)
        {
            pnlEveryDay.Enabled = rBtnDay.Checked;
            Sett.Schd.Mode = ScheduleMode.EveryDay;
        }

        private void rBtnHour_CheckedChanged(object sender, EventArgs e)
        {
            pnlEveryHour.Enabled = rBtnHour.Checked;
            Sett.Schd.Mode = ScheduleMode.EveryHour;
        }

        private void rBtnPeriod_CheckedChanged(object sender, EventArgs e)
        {
            pnlEveryPeriod.Enabled = rBtnPeriod.Checked;
            Sett.Schd.Mode = ScheduleMode.EveryPeriod;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (txbSourceDir.Text.Trim() == "" || txbDestDir.Text.Trim() == "")
            {
                MessageBox.Show("Не выбран один или оба каталога");
                return;
            }
            if (txbSourceDir.Text.Trim().ToUpper() == txbDestDir.Text.Trim().ToUpper())
            {
                MessageBox.Show("Выбраные каталоги не могут быть одинаковыми");
                return;
            }
            if (txbSourceDir.Text.Trim().ToUpper().Contains(txbDestDir.Text.Trim().ToUpper()) || txbDestDir.Text.Trim().ToUpper().Contains(txbSourceDir.Text.Trim().ToUpper()))
            {
                MessageBox.Show("Выбранные каталоги не могут входить один в другой");
                return;
            }

            Sett.SourceDir = txbSourceDir.Text.Trim();
            Sett.DestDir = txbDestDir.Text.Trim();

            Sett.Mode = rBtnSync.Checked ? ElementMode.Mirror : ElementMode.Archive;
            Sett.DualSync = chbxDualSync.Checked;
            Sett.ArchMode = rBtnArchDiff.Checked ? ArchiveMode.Diff : ArchiveMode.Inc;
            Sett.LineSize = (byte)numArchLineSize.Value;
            Sett.LinesCount = (byte)numArchLinesCount.Value;

            if (rBtnDay.Checked)
            {
                if (!new List<bool>(Sett.Schd.DaysOfWeek).Contains(true))
                {
                    MessageBox.Show("Не выбрано ни одного дня");
                    return;
                }
                if (!TryParseTime(txbDay_StartTime.Text, out Sett.Schd.TimeOfDay))
                {
                    MessageBox.Show("Неверный формат времени");
                    return;
                }
            }

            if (rBtnHour.Checked)
            {
                if (!new List<bool>(Sett.Schd.Hours).Contains(true))
                {
                    MessageBox.Show("Не выбрано ни одного часа");
                    return;
                }
                Sett.Schd.Minute = (byte)numHour_Min.Value;
            }

            if (rBtnPeriod.Checked)
            {
                if (numD.Value == 0 && numH.Value == 0 && numM.Value == 0 && numS.Value == 0)
                {
                    MessageBox.Show("Не выбран период");
                    return;
                }
                int sec;
                if (!TryParseTime(txbPeriod_StartTime.Text, out sec))
                {
                    MessageBox.Show("Неверный формат времени");
                    return;
                }
                Sett.Schd.StartDate = cldPeriod_StartDate.Value.Date.AddSeconds(sec);
                Sett.Schd.Period = (int)(numD.Value * 86400 + numH.Value * 3600 + numM.Value * 60 + numS.Value);
            }

            bOK = true;
            Close();
        }

        bool TryParseTime(string Time, out int Seconds)
        {
            Seconds = 0;
            string[] sl = Time.Trim().Split(':');
            int hour, min;
            if (sl.Length != 2 || !int.TryParse(sl[0], out hour) || !int.TryParse(sl[1], out min))
                return false;
            Seconds = hour * 3600 + min * 60;
            return true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void chbxEnableSchedule_CheckedChanged(object sender, EventArgs e)
        {
            if (chbxEnableSchedule.Checked)
            {
                grSchedule.Enabled = true;
            }
            else
            {
                grSchedule.Enabled = false;
                Sett.Schd.Mode = ScheduleMode.None;
                rBtnDay.Checked = false;
                rBtnHour.Checked = false;
                rBtnPeriod.Checked = false;
            }
        }

        private void rBtnMode_CheckedChanged(object sender, EventArgs e)
        {
            grArchSettings.Visible = rBtnArch.Checked;
            label9.Text = rBtnArch.Checked ? "Каталог архива" : "Каталог - зеркало";
        }

        private void btnSourceDirSelect_Click(object sender, EventArgs e)
        {
            if (dlgFolder.ShowDialog() == DialogResult.OK)
                txbSourceDir.Text = dlgFolder.SelectedPath;
        }

        private void btnDestDirSelect_Click(object sender, EventArgs e)
        {
            if (dlgFolder.ShowDialog() == DialogResult.OK)
                txbDestDir.Text = dlgFolder.SelectedPath;
        }



    }
}
